Using Regular Expressions in Macromedia Central
Table of Contents
Regular Expressions Explained
Quite simply, regular expressions are text patterns. They are generally searched for in strings of text and can be used in different ways to return a large variety of results. A regular expression can be as simple as a string—for example, "hello". You could then search another large amount of text to see if this pattern exists. Regular expressions also possess powerful notations that allow you to specify any possible type of pattern, such as "a word starting with h and ending with o," "a word that is all lowercase," "a word containing double letters," or "a word containing five letters." Virtually any pattern is possible.
Regular expressions can help you greatly. Consider the task of parsing a URL with a query string—for example:
http://my.company.com/some/path.html?foo=$_hello&bar=world&test=test@test.com
Your task is to find the first variable whose corresponding value is a valid e-mail address.
Parsing this information using string functions would be painful and would probably require many commands and a loop, like so:
// string function version
var url = "http://my.company.com/some/path.html?foo=_hello&bar=world&test=test@test.com";
var varString = url.split("?")[1];
var pairs = varString.split("&");
var result = new Array();
for (each in pairs) {
var tmp = pairs[each].split("=");
var name = tmp[0];
var value = tmp[1];
if ((value.indexOf("@") > 0) &&
(value.lastIndexOf(".") > value.indexOf("@")) &&
(value.indexOf("@") == value.lastIndexOf("@"))) {
// found one!
result.push(name);
result.push(value);
break;
}
}
Compare the previous code with a version using a regular expression. You're not necessarily going to be able to understand it yet, but you can notice the sizable difference:
// regular expression version
var url = "http://my.company.com/some/path.html?foo=$_hello&bar=world&test=test@test.com";
var re = new RegExp("(\\w+)=(\\w+@[\\w\\.]+)\\b");
var result = re.match(url);
Regular expressions may look confusing but they can do the job of many commands at once. In addition to matching and returning the matched portion(s) of interest, regular expressions can be used to test if a pattern exists and replace matched strings with another. I'll cover that later but first let's try to decipher some regular expression syntax.